package com.example.littlepainter.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream

class FileUtils {
    /**将bitmap保存到文件中*/
    suspend fun saveBitmap(bitmap: Bitmap):String = withContext(Dispatchers.IO){
        //文件名  以时间为文件名
        val name = TimeUtils.timeName()
        //文件路径
        val path = "${Helper.mContext.get()!!.filesDir}/$name"
        //创建并写入
        BufferedOutputStream(FileOutputStream(path)).use { bos ->
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos)
        }
        //返回当前路径
        path
    }

    //加载原图
   suspend fun loadBitmapFromPath(path:String):Bitmap = withContext(Dispatchers.IO){
       BitmapFactory.decodeFile(path)
   }

    suspend fun deleteFile(path: String)= withContext(Dispatchers.IO){
        File(path).also {
            if (it.exists()) it.delete()
        }
    }
}